import tkinter as tk
from tkinter import messagebox
from tkinter import ttk  # 引入 ttk 模块以使用美化控件
from social_network_utils import StudentList, parse_student_file
import os


class SocialNetworkApp:
    def __init__(self, master, student_list):
        self.master = master
        master.title("Social Network System")
        master.geometry("500x400")  # Set window size
        master.configure(bg="#f0f0f0")  # Set background color

        self.student_list = student_list

        self.create_widgets()

    def create_widgets(self):
        style = ttk.Style()
        style.configure("TLabel", font=("Arial", 12), background="#f0f0f0")
        style.configure("TButton", font=("Arial", 10), padding=5)
        style.configure("TEntry", font=("Arial", 10))

        # Add title
        ttk.Label(self.master, text="Social Network System", font=("Arial", 16, "bold"), anchor="center").grid(row=0, column=0, columnspan=2, pady=10)

        # Add separator
        ttk.Separator(self.master, orient="horizontal").grid(row=1, column=0, columnspan=2, sticky="ew", pady=5)

        # Username input
        ttk.Label(self.master, text="Username:").grid(row=2, column=0, padx=10, pady=10, sticky="w")
        self.entry_username = ttk.Entry(self.master, width=30)
        self.entry_username.grid(row=2, column=1, padx=10, pady=10)

        # New friend username input
        ttk.Label(self.master, text="New Friend Username:").grid(row=3, column=0, padx=10, pady=10, sticky="w")
        self.entry_new_friend = ttk.Entry(self.master, width=30)
        self.entry_new_friend.grid(row=3, column=1, padx=10, pady=10)

        # Interest input
        ttk.Label(self.master, text="Interest:").grid(row=4, column=0, padx=10, pady=10, sticky="w")
        self.entry_interest = ttk.Entry(self.master, width=30)
        self.entry_interest.grid(row=4, column=1, padx=10, pady=10)

        # Community 1 usernames input
        ttk.Label(self.master, text="Community 1 Usernames (comma-separated):").grid(row=5, column=0, padx=10, pady=10, sticky="w")
        self.entry_community1 = ttk.Entry(self.master, width=30)
        self.entry_community1.grid(row=5, column=1, padx=10, pady=10)

        # Community 2 usernames input
        ttk.Label(self.master, text="Community 2 Usernames (comma-separated):").grid(row=6, column=0, padx=10, pady=10, sticky="w")
        self.entry_community2 = ttk.Entry(self.master, width=30)
        self.entry_community2.grid(row=6, column=1, padx=10, pady=10)

        # Add separator
        ttk.Separator(self.master, orient="horizontal").grid(row=7, column=0, columnspan=2, sticky="ew", pady=5)

        # Buttons
        ttk.Button(self.master, text="Display Friends", command=self.display_friends).grid(row=8, column=0, padx=10, pady=10)
        ttk.Button(self.master, text="Add Friend", command=self.add_friend).grid(row=8, column=1, padx=10, pady=10)
        ttk.Button(self.master, text="Filter Students", command=self.filter_students).grid(row=9, column=0, padx=10, pady=10)
        ttk.Button(self.master, text="Find Bridges", command=self.find_bridges).grid(row=9, column=1, padx=10, pady=10)

        # Set minimum window size
        self.master.minsize(500, 400)

    def display_friends(self):
        username = self.entry_username.get().strip()  # Remove whitespace
        if not username:
            messagebox.showerror("Error", "Please enter a username.")
            return
        student = self.student_list.find_student_by_username(username)
        if student:
            friends = student.get_friends(self.student_list.students.to_list())
            friend_names = [friend.fullName for friend in friends]
            messagebox.showinfo("Friends", "\n".join(friend_names))
        else:
            messagebox.showerror("Error", f"No student found with username {username}. Please check and try again.")

    def add_friend(self):
        username = self.entry_username.get().strip()
        new_friend_username = self.entry_new_friend.get().strip()

        if not username or not new_friend_username:
            messagebox.showerror("Error", "Please enter both username and new friend's username.")
            return

        student = self.student_list.find_student_by_username(username)
        if student:
            student.add_friend(new_friend_username)

            # Reload student data and update StudentList
            updated_students = parse_student_file('C:/Users/lenovo/Desktop/ressources/social_network_system/students.json')
            self.student_list = StudentList()
            for student in updated_students:
                self.student_list.add_student(student)

            messagebox.showinfo("Success", f"Friend {new_friend_username} has been successfully added to {student.fullName}'s friend list.")
        else:
            messagebox.showerror("Error", f"No student found with username {username}. Please check and try again.")

    def filter_students(self):
        interest = self.entry_interest.get()
        students = self.student_list.filter_students_by_interest(interest)
        student_names = [student.fullName for student in students]
        if student_names:
            messagebox.showinfo("Filtered Students", "\n".join(student_names))
        else:
            messagebox.showinfo("No Results", f"No students found with interest {interest}.")

    def find_bridges(self):
        community1_usernames = self.entry_community1.get().split(',')
        community2_usernames = self.entry_community2.get().split(',')
        community1 = self.student_list.create_community(community1_usernames)
        community2 = self.student_list.create_community(community2_usernames)
        bridges = self.student_list.find_bridges(community1, community2)
        bridge_names = [bridge.fullName for bridge in bridges]
        if bridge_names:
            messagebox.showinfo("Bridges", "\n".join(bridge_names))
        else:
            messagebox.showinfo("No Bridges", "No bridges found between the communities.")

if __name__ == "__main__":
    # Ensure students.json exists before parsing
    if not os.path.exists('C:/Users/lenovo/Desktop/ressources/social_network_system/students.json'):
        with open('C:/Users/lenovo/Desktop/ressources/social_network_system/students.json', 'w', encoding='utf-8') as file:
            file.write('{"students": []}')

    # Parse the student data file
    students = parse_student_file('C:/Users/lenovo/Desktop/ressources/social_network_system/students.json')

    # Create StudentList and add students
    student_list = StudentList()
    for student in students:
        student_list.add_student(student)

    root = tk.Tk()
    app = SocialNetworkApp(root, student_list)
    root.mainloop()
